package com.woniuxy.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.woniuxy.entity.Order;
import com.woniuxy.entity.OrderItem;
import com.woniuxy.entity.UserCart;
import com.woniuxy.entity.dto.ChartAndAddrDTO;
import com.woniuxy.mapper.OrderMapper;
import com.woniuxy.producer.DelayProducer;
import com.woniuxy.service.OrderService;
import com.woniuxy.util.GetUserIdFromToken;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.SnowflakeIdGenerator;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @BelongsProject: pigTrotterStore
 * @BelongsPackage: com.woniuxy.service
 * @Author: Quan
 * @Date: 2025/3/17 20:06
 */
@Service
public class OrderServiceImpl implements OrderService {
	@Resource
	private OrderMapper orderMapper;

	@Resource
	private DelayProducer delayProducer;

	@Resource
	private RedisTemplate<String, Object> redisTemplate;

	/**
	 * @Description: 添加账单
	 * @Param: [chartAndAddrDTO]
	 * @return: com.woniuxy.util.ResponseData<?>
	 * @Author: Quan
	 * @Date: 2025/3/17
	 * 1、判断库存是否足够
	 * 2、通过chartIdList对购物车内物品批量查询
	 * 3、生成账单
	 * 4、生成项目详情
	 */
	@Override
	public ResponseData<?> addOrder(ChartAndAddrDTO chartAndAddrDTO) throws ParseException, InterruptedException {
//		1、判断库存够不够，先通过chatIc进行连表查询
		List<UserCart> cartList = orderMapper.queryChartByIds(chartAndAddrDTO.getChartIdList());
		List<String> lackCountNameList = cartList.stream()
				.filter(item -> item.getBuyNum() > item.getStoreCount())
				.map(UserCart::getName)
				.collect(Collectors.toList());
		if (!CollectionUtil.isEmpty(lackCountNameList)) {
			return ResponseData.ok(lackCountNameList);
		}

		// 将被点击的购物车系统放入订单中
		Order order = new Order();
		order.setAddressId(chartAndAddrDTO.getAddrId());
		Integer userId = GetUserIdFromToken.getUserId();
		order.setUserId(userId);
		BigDecimal price = BigDecimal.ZERO;
		for (UserCart userCart : cartList) {
			price = price.add(userCart.getTotalPrice());
		}
		order.setTotalPrice(price);
		// 配置雪花id
		SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator();
		String snowId = String.valueOf(snowflakeIdGenerator.nextId());
		order.setOrderNum(snowId);
		orderMapper.addOrder(order);

		// 添加order详情表
		List<OrderItem> orderItems = new ArrayList<>();
		for (UserCart userCart : cartList) {
			OrderItem orderItem = new OrderItem();
			orderItem.setSumPrice(userCart.getTotalPrice());
			orderItem.setOrderId(order.getOrderNum());
			orderItem.setPrice(userCart.getBuyPrice());
			orderItem.setBuyCount(userCart.getBuyNum());
			orderItem.setFoodId(userCart.getFoodId());
			orderItem.setFoodName(userCart.getName());
			orderItems.add(orderItem);
		}
		// 批量添加到order详情中
		orderMapper.batchAddOrderItem(orderItems);

		// 批量删除库存
		orderMapper.batchUpdateFood(cartList);

		// 批量更新订单状态
		orderMapper.batchUpdateCart(chartAndAddrDTO.getChartIdList());

		// 延迟订单，进行15min的判断
		redisTemplate.opsForValue().set(order.getOrderNum(), order.getOrderNum(), 10, TimeUnit.MINUTES);
		delayProducer.send("delayInsertOrder", snowId, 5000);

		return ResponseData.ok();
	}
}
